package com.hfjava.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/Login")
public class LoginServlet extends HttpServlet {
    private ServletContext application;

    @Override
    public void init() throws ServletException {
        application = this.getServletContext();
    }

    public synchronized void setCount() throws ServletException {
        if (application == null){
            init();
        }
        if (application.getAttribute("peopleCount") == null){
           application.setAttribute("peopleCount",1);
        }else{
            int count = (Integer)application.getAttribute("peopleCount");
            application.setAttribute("peopleCount",++count);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(1800);
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String saveTime = request.getParameter("saveTime");
        if (userName.equalsIgnoreCase("admin") && password.equals("123")){
            String userInfo = userName + "-" + password;
            Cookie cookie = new Cookie("user",userInfo);
            cookie.setHttpOnly(true);//防止其他地方劫持cookie，如js中
            if (saveTime.equals("no")){
                cookie.setMaxAge(0);
            }else if (saveTime.equals("day")){
                cookie.setMaxAge(24* 3600);
            }else if (saveTime.equals("week")){
                cookie.setMaxAge(24 * 3600 * 7);
            }else {
                cookie.setMaxAge(24 * 3600 * 30);
            }
            response.addCookie(cookie);
            session.setAttribute("username",userName);
            session.setAttribute("password",password);
            setCount();
            request.getRequestDispatcher("/home.jsp").forward(request,response);
        }else{
            session.setAttribute("errorMsg","登录失败，用户名或密码错误");
            response.sendRedirect("login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
